package org.msn.gui.controller;

import javafx.application.Platform;
import javafx.embed.swing.SwingFXUtils;
import javafx.fxml.FXML;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
import lombok.SneakyThrows;
import org.msn.gui.init.ParentInit;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.URL;
import java.util.ResourceBundle;

public class OtherVideoController extends ParentInit {
    private ImageView imageView = new ImageView();
    public volatile static boolean stop = false;

    @FXML
    private GridPane root;

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        root.add(imageView, 0, 0);
        new OtherVideoThread().start();
    }

    public class OtherVideoThread extends Thread {
        @SneakyThrows
        @Override
        public void run() {
            DatagramSocket datagramSocket = new DatagramSocket(Integer.parseInt(
                    ctx.channel().localAddress().toString().split(":")[1]));

            while (stop) {
                byte[] bytes = new byte[65507];
                DatagramPacket datagramPacket = new DatagramPacket(bytes, 65507);
                datagramSocket.receive(datagramPacket);

                ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(datagramPacket.getData());
                BufferedImage otherImage = ImageIO.read(byteArrayInputStream);

                if (otherImage == null) {
                    continue;
                }

                Image image = SwingFXUtils.toFXImage(otherImage, null);
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        imageView.setImage(image);
                    }
                });
            }
        }
    }
}
